﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Custom.Framework
{
    /// <summary>
    /// 日志工具类
    /// </summary>
    public class Logger
    {
        #region 私有变量
        /// <summary>
        /// 线程安全队列
        /// </summary>
        private static readonly ConcurrentQueue<LogMessage> _queue;

        /// <summary>
        /// 信号
        /// </summary>
        private static readonly ManualResetEvent _mre;

        /// <summary>
        /// 日志写锁
        /// </summary>
        private static readonly ReaderWriterLockSlim _lock;

        /// <summary>
        /// 日志保存的路径
        /// </summary>
        private static readonly string _logDir;

        /// <summary>
        /// 显示的日志级别
        /// </summary>
        private static readonly string[] _levelArray;

        #endregion

        #region 构造函数
        /// <summary>
        /// 构造函数
        /// </summary>
        static Logger()
        {
            _queue = new ConcurrentQueue<LogMessage>();
            _mre = new ManualResetEvent(false);
            _lock = new ReaderWriterLockSlim();
            _levelArray = new string[] { };

            _logDir = AppDomain.CurrentDomain.BaseDirectory + @"Logs";
            _levelArray = @"*".Split(',');


            Task.Factory.StartNew(() => Initialize(), TaskCreationOptions.LongRunning);
        }
        #endregion

        #region 信息日志
        /// <summary>
        /// 信息日志
        /// </summary>
        /// <param name="message">日志内容</param>
        /// <param name="args">字符串格式化参数</param>
        public static void Info(string message, params object[] args)
        {
            var sf = new StackTrace(true).GetFrame(1);
            StringBuilder builder = new StringBuilder();
            if (args != null)
            {
                //--- 其他的参数 ---
                foreach (var parm in args)
                {
                    builder.Append("\r\n");
                    builder.Append(parm.ToString());
                }
            }
            var logMessage = new LogMessage
            {
                Level = LogLevel.Info,
                //Message = string.Format(Regex.Replace(message?.Replace("{", "{{").Replace("}", "}}") ?? "", @"{{(\d+)}}", "{$1}"), args),
                Message = message + builder.ToString(),
                StackFrame = sf
            };
            if (_levelArray.Contains("*") || _levelArray.Contains("info"))
            {
                _queue.Enqueue(logMessage);
                _mre.Set();
            }
        }
        #endregion

        #region 错误日志
        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="ex">错误Exception</param>
        /// <param name="message">自定义信息</param>
        /// <param name="args">字符串格式化参数</param>
        public static void Error(string message, params object[] args)
        {
            var sf = new StackTrace(true).GetFrame(1);
            StringBuilder builder = new StringBuilder();
            if (args != null)
            {
                //--- 其他的参数 ---
                foreach (var parm in args)
                {
                    builder.Append("\r\n");
                    builder.Append(parm.ToString());
                }
            }
            var logMessage = new LogMessage
            {
                Level = LogLevel.Error,
                Message = message + builder.ToString(),
                StackFrame = sf
            };

            if (_levelArray.Contains("*") || _levelArray.Contains("error"))
            {
                _queue.Enqueue(logMessage);
                _mre.Set();
            }
        }

        /// <summary>
        /// 错误日志
        /// </summary>
        /// <param name="ex">错误Exception</param>
        /// <param name="message">自定义信息</param>
        /// <param name="args">字符串格式化参数</param>
        public static void Error(Exception ex, string message = "", params object[] args)
        {
            StackFrame sf = null;
            if (ex != null)
            {
                var frames = new StackTrace(ex, true).GetFrames();
                sf = frames?[frames.Length - 1];
            }
            else
            {
                sf = new StackTrace(true).GetFrame(1);
            }
            StringBuilder builder = new StringBuilder();
            if (args != null)
            {
                //--- 其他的参数 ---
                foreach (var parm in args)
                {
                    builder.Append("\r\n");
                    builder.Append(parm.ToString());
                }
            }
            var logMessage = new LogMessage
            {
                Level = LogLevel.Error,
                Exception = ex,
                //  Message =      string.Format(Regex.Replace(message?.Replace("{", "{{").Replace("}", "}}") ?? "", @"{{(\d+)}}", "{$1}"), args),
                Message = message + builder.ToString(),
                StackFrame = sf
            };
            if (_levelArray.Contains("*") || _levelArray.Contains("error"))
            {
                _queue.Enqueue(logMessage);
                _mre.Set();
            }
        }
        #endregion

        #region 删除日志

        /// <summary>
        /// 删除日志 默认删除7天前的
        /// </summary>
        public static void Delete()
        {
            DateTime deadDate = DateTime.Now.AddDays(-7);
            DeleteLog(deadDate);
        }

        /// <summary>
        /// 根据指定日志删除日志
        /// </summary>
        /// <param name="dateDeadLine"></param>
        public static void Delete(DelDeadLine dateDeadLine)
        {
            DateTime deadDate = DateTime.Now.AddDays(-7);

            switch (dateDeadLine)
            {
                case DelDeadLine.Week:
                    deadDate = DateTime.Now.AddDays(-7);
                    break;
                case DelDeadLine.HalfMonth:
                    deadDate = DateTime.Now.AddDays(-15);
                    break;
                case DelDeadLine.Month:
                    deadDate = DateTime.Now.AddMonths(-1);
                    break;
                case DelDeadLine.ThreeMonth:
                    deadDate = DateTime.Now.AddMonths(-3);
                    break;
                case DelDeadLine.HalfYear:
                    deadDate = DateTime.Now.AddMonths(-6);
                    break;
                case DelDeadLine.Year:
                    deadDate = DateTime.Now.AddYears(-1);
                    break;
                default:
                    deadDate = DateTime.Now.AddDays(-7);
                    break;
            }
            DeleteLog(deadDate);
        }
        #endregion

        #region 私有方法/实体

        #region 删除日志

        private static void DeleteLog(DateTime deadDate)
        {
            Task.Factory.StartNew(obj =>
            {
                if (!Directory.Exists(_logDir)) { return; }
                DateTime _deadDate = Convert.ToDateTime(obj);
                DirectoryInfo folder = new DirectoryInfo(_logDir);
                foreach (FileInfo file in folder.GetFiles("*.log", SearchOption.AllDirectories))
                {
                    if (file.CreationTime < _deadDate)
                    {
                        try
                        {
                            File.Delete(file.FullName);
                        }
                        catch { }
                    }
                }
            }, deadDate);
        }

        #endregion

        #region 日志初始化
        /// <summary>
        /// 日志初始化
        /// </summary>
        private static void Initialize()
        {
            while (true)
            {
                //等待信号通知
                _mre.WaitOne();
                //写入日志
                Write();
                //重新设置信号
                _mre.Reset();
                Thread.Sleep(1);
            }
        }
        #endregion

        #region 写入日志
        /// <summary>
        /// 写入日志
        /// </summary>
        private static void Write()
        {
            //根据当天日期创建日志文件
            var fileName = $"{DateTime.Now.ToString("yyyy-MM-dd")}.log";
            try
            {
                //进入写锁
                _lock.EnterWriteLock();
                LogMessage logMessage = new LogMessage();
                //判断日志队列中是否有内容，从列队中获取内容，并删除列队中的内容
                while (_queue?.Count > 0 && _queue.TryDequeue(out logMessage))
                {
                    //判断目录是否存在，不存在则重新创建
                    string _dir = Path.Combine(_logDir, logMessage.Level.ToString("g"));
                    if (!Directory.Exists(_dir)) Directory.CreateDirectory(_dir);
                    string _path = Path.Combine(_dir, fileName);

                    using (var sw = new StreamWriter(_path, true, Encoding.UTF8))
                    {
                        var sf = logMessage.StackFrame;
                        sw.WriteLine($"[时间：{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.ffff")}]");
                        sw.WriteLine($"[类名：{sf?.GetMethod().DeclaringType.FullName}]");
                        sw.WriteLine($"[方法：{sf?.GetMethod().Name}]");
                        sw.WriteLine($"[行号：{sf?.GetFileLineNumber()}]");
                        if (!string.IsNullOrEmpty(logMessage.Message))
                        {
                            sw.WriteLine($"[内容：{logMessage.Message}]");
                        }
                        if (logMessage.Exception != null)
                        {
                            sw.WriteLine($"[异常source：{logMessage.Exception.Source}]");
                            sw.WriteLine($"[异常：{logMessage.Exception.ToString()}]");
                        }
                        sw.WriteLine("------------------------------------------------------------------------------------------");
                        sw.WriteLine(string.Empty);
                    }
                }
            }
            finally
            {
                //退出写锁
                _lock.ExitWriteLock();
            }
        }
        #endregion

        #region 获取物理路径
        /// <summary>
        /// 获取物理路径
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        private static string GetPhysicalPath(string path)
        {
            var physicalPath = AppDomain.CurrentDomain.BaseDirectory;
            if (!string.IsNullOrEmpty(path))
            {
                path = path.Replace("~", "").Replace("/", @"\").TrimStart('\\').TrimEnd('\\');
                var start = path.LastIndexOf('\\') + 1;
                var length = path.Length - start;
                physicalPath = Path.Combine(physicalPath, path.Substring(start, length).Contains(".") ? path : path + @"\");
            }
            return physicalPath;
        }
        #endregion

        #region 日志实体
        /// <summary>
        /// 日志级别
        /// </summary>
        private enum LogLevel
        {
            Info,
            Error
        }

        /// <summary>
        /// 消息实体
        /// </summary>
        private class LogMessage
        {
            /// <summary>
            /// 日志级别
            /// </summary>
            public LogLevel Level { get; set; }

            /// <summary>
            /// 消息内容
            /// </summary>
            public string Message { get; set; }

            /// <summary>
            /// 异常对象
            /// </summary>
            public Exception Exception { get; set; }

            /// <summary>
            /// 堆栈帧信息
            /// </summary>
            public StackFrame StackFrame { get; set; }
        }



        /// <summary>
        /// 日志删除截止日期
        /// </summary>
        public enum DelDeadLine
        {
            /// <summary>
            /// 一周之前
            /// </summary>
            Week,
            /// <summary>
            /// 半月
            /// </summary>
            HalfMonth,
            /// <summary>
            /// 一月
            /// </summary>
            Month,

            /// <summary>
            /// 三个月
            /// </summary>
            ThreeMonth,

            /// <summary>
            /// 半年
            /// </summary>
            HalfYear,
            /// <summary>
            /// 年
            /// </summary>
            Year
        }
        #endregion

        #endregion
    }
}
